<?php
namespace app\index\controller;

use \think\Cache;
use \think\Controller;
use think\Loader;
use think\Db;
use \think\Request;
use \think\Session;
use Firebase\JWT\JWT;

class Common extends Controller
{
	
	public function createJwt($userId)
    {
        $key = md5('xxxxxxx'); //jwt的签发密钥，验证token的时候需要用到
        $time = time(); //签发时间
        $expire = $time + 60*60*24*30; //过期时间
        $token = array(
            "userid" => $userId,
            "iss" => "http://shfw.zifengye.cn",//签发组织
            "aud" => "http://shfw.zifengye.cn", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwt = JWT::encode($token, $key);
        return $jwt;
    }

    public function login()
    {
    	if($this->request->post()) {
	            //是提交操作
	            $post = $this->request->post();
	            //验证用户名是否存在
	            $name = Db::name('user')->where('username',$post['username'])->where('password',$post['password'])->find();
	            if(empty($name)) {
	            	$result['code'] = -1;
	            	$result['msg'] = '用户名不存在';
	            	return json_encode($result);
	            }
	            $data['access_token'] = self::createJwt($name['id']);
	            $data['user'] = $name;
	            $result['code'] = 0;
	            $result['msg'] = '登录成功';
	            $result['data'] = $data;
	            return json_encode($result);
    	}
    }


}
